How do you find the square root of a number in C?
You write a function that evaluates the square root of its argument and returns the result to the caller.
You can also use the run-time library functions in math.h ...
double sqrt (double x);
double pow (double x, (double) 0.5);
Difference between fgets and gets?
gets is an insecure function, its careless use can lead to errors. If you
want to use gets, consider using fgets instead, supplying stdin as
the file reference parameter.
The gets function waits until a line of input is available (unless one is already
available), and consumes the whole line including the ENTER/newline at the end.
The characters on the line are stored in the string parameter, except for the
ENTER/newline, which is discarded.
returns NULL on end-of-file, otherwise the parameter s.
The parameter given to gets must be an already allocated array of characters, not an
uninitialised char * pointer; gets will never allocate memory.
{ char a[100]; gets(line); // This is correct
{ char a[100]; char *s; s=a; gets(s); // This is correct
{ char *s; s=new char[100]; gets(s); // This is correct
{ char *s; gets(s); // This is WRONG
The array given to gets must be big enough to hold any line that could conceivably be
input. C++ and C are incapable of telling how long an array is. If it is not long enough
for the data that is read, other data (and perhaps program code) will be overwritten.
Thus gets is not a safe function for use in critical applications.
What is the C plus plus program for regula falsi method?
#include
#include
#include
/* define prototype for USER-SUPPLIED function f(x) */
double ffunction(double x);
/* EXAMPLE for "ffunction" */
double ffunction(double x)
{
return (x * sin(x) - 1);
}
/* -------------------------------------------------------- */
/* Main program for algorithm 2.3 */
void main()
{
double Delta = 1E-6; /* Closeness for consecutive iterates */
double Epsilon = 1E-6; /* Tolerance for the size of f(C) */
int Max = 199; /* Maximum number of iterations */
int Satisfied = 0; /* Condition for loop termination */
double A, B; /* INPUT endpoints of the interval [A,B] */
double YA, YB; /* Function values at the interval-borders */
int K; /* Loop Counter */
double C, YC; /* new iterate and function value there */
double DX; /* change in iterate */
printf("-----------------------------------------------------\n");
printf("Please enter endpoints A and B of the interval [A,B]\n");
printf("EXAMPLE : A = 0 and B = 2. Type: 0 2 \n");
scanf("%lf %lf", &A, &B);
printf("The interval ranges from %lf to %lf\n", A,B);
YA = ffunction(A); /* compute function values */
YB = ffunction(B);
/* Check to see if YA and YB have same SIGN */
if( ( (YA >= 0) && (YB >=0) ) ( (YA < 0) && (YB < 0) ) ) {
printf("The values ffunction(A) and ffunction(B)\n");
printf("do not differ in sign.\n");
exit(0); /* exit program */
}
for(K = 1; K <= Max ; K++) {
if(Satisfied 0) { /* first 'if' */
Satisfied = 1; /* Exact root is found */
}
else if( ( (YB >= 0) && (YC >=0) ) ( (YB < 0) && (YC < 0) ) ) {
B = C; /* Squeeze from the right */
YB = YC;
}
else {
A = C; /* Squeeze from the left */
YA = YC;
}
if( (fabs(DX) < Delta) && (fabs(YC) < Epsilon) ) Satisfied = 1;
} /* end of 'for'-loop */
printf("----------------------------------------------\n");
printf("The number of performed iterations is : %d\n",K - 1);
printf("----------------------------------------------\n");
printf("The computed root of f(x) = 0 is : %lf \n",C);
printf("----------------------------------------------\n");
printf("Consecutive iterates differ by %lf\n", DX);
printf("----------------------------------------------\n");
printf("The value of the function f(C) is %lf\n",YC);
} /* End of main program */
Why you use linked list instead of arrays?
You would use linked lists instead of arrays in two instances:
1) You don't know how long your list will be and it is apt to dramatically change length.
2) You will make lots of additions and removals in the middle of your list.
Why is c language said to be portable?
Well, C is not platform dependent. You can compile C into source code on a Windows, Mac, Unix or any other operating system as long as you are using that type of computer. You could write code that can be compiled on almost any operating system. But the programs you write may or may not be able to move from system to system based on whether or not you use tools specific to that operating system. Java is not actually platform independent either because you need JVM to run it. It's just that most computers come with JVM installed.
Both of the above are wrong. The C language specification itself is platform-dependent, as there are numerous places where ambiguities (both intentional and unintentional) cause different behavior according to how both the platform AND the C-compiler writer chose to behave. Thus, while it is possible to write a C program which is highly-portable, that program is still dependent on the exact implementation of the C compiler and OS it runs on. So, the behavior of a C program depends on the platform.
The Java Language is platform INDEPENDENT, since it does NOT have the implementation ambiguities of C, and has a completely-standardized interface to all platforms (the JVM spec). Naturally, the JVM program is plaform dependent, as creating it to conform to the Java VM specification requires knowledge of the peculiarities of the platform.
Why to use header file to easy know?
in the java as we use the inheritance property in the same way we can get the the inheritance property in c by using the prepared header files( .h files).
there a single program in c use the many methods of many header files like math.h give us to use the use of floor(), sqrt() e.t.c. functions..
Write a program to display the multiplication table for a given integer up to 10 using a 'for' loop?
The for loop looks like this:
for (i = 1; i <= 10; i++)
{
...
}
This will repeat anything inside ten times; the variable "i" will have the values 1, 2, ...10. The first part is the initial assignment, the second part specifies a condition - while it is true, the loop should continue, and the third part increments the variable(s).
Replace the "..." with anything you want to repeat 10 times, for example, a System.out.println(...) that involves the variable "i".
What is insertion sorts in worst case time?
Best case for insertion sort is O(n), where the array is already sorted. The worst case, where the array is completely reversed, is O(n*n).
The data structures are user defined data types specifically created for the manipulation of data in a predefined manner. Examples of data structures would be stacks,queues,trees,graphs and even arrays(also reffered as data structure)
Program to print greatest of three numbers?
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("enter the three numbers: ");
scanf(%d%d%d:,&a&b&c);
if(a>b | a>c)
{
printf("the greatest no: is %d",a);
}
if(b>c)
{
printf("the greatest no: is %d",b);
}
else
{
printf("the greatest no: is %d",c);
}
getch();
}
How do you define variable size array in c?
Array is the set of multiple values while variable is used to store a single value at a time.
Arrays have subscript while variable doesn't have a subscript.
Syntax of declaring array and variable is different.
For variable:
data_type list of variables;
For array:
Data_type variable1[size], variablen[size];
C program to find factorial of a given number using pointers?
/*** returns N!, assume N >= 0 ***/
int Factorial(int n) {
if (n <=1 ) /* 0! = 1! = 1 */ return 1;
/** you can place as many know values as you want, like 2!, 3!, etc **/
/** but, recursive call will do just fine, ... **/
return n * Factorial(n - 1); /** compute N * (N-1)! **/
}
What are the advantages of using string in c plus plus?
I assume you mean std::string rather than strings in general. Programs that need to convey any information to the user will usually require many strings, and when retreiving input from the user, a string (in conjunction with a string stream) are the best way of checking that data before processing it. The std::string (and its wide-character counterpart, std::wstring) needn't be used for all strings, of course, but they are much easier to work with when strings need additional processing, such as when concatenating strings, or searching within strings. And if you need more functionality than is provided by std::string alone, you can always derive a new string object from std::string and embelish it as required. Of course, if you require less functionality than is provided by std::string then you have the option of creating your own lightweight string class from scratch. However, for most applications, std::string is lightweight enough, and if you use std::string at all, then there's little point in writing your own string class. Aside from re-inventing the wheel (one of the reasons the STL exists), it's only going to increase your code size. However, for new programmers, it can be an interesting excercise creating your own string class, if only to show how std::string works and why re-inventing wheels is rarely a good thing.
Why did c plus plus become more popular inspite of so many object oriented languages available?
All languages are interesting to some degree or another. Programming languages in particular allow us humans to communicate with and ultimately control computers, bending them to our will. However, some languages are better than others for certain tasks. C++ is a general purpose, cross-platform, high-level language that can produce highly-efficient machine code (the native language of the computer). What makes it interesting is subjective -- each programmer will have their own likes and dislikes -- but ultimately the language gives a high-degree of control over the hardware, exploiting specific features of the architecture.
The same kind of thing can be achieved using Assembly Language (a low-level language), and in many ways would be regarded as a more interesting language than C++. But it is extremely difficult to work with. Even if you have access to a vast library of pre-written routines, you still require intimate knowledge of the underlying hardware and must write programs in minute detail. C++ can achieve similar results, but the abstraction between the hardware and the code you write is such that you needn't concern yourself with the hardware quite so much. That is, a single instruction in C++ can easily generate dozens of assembly instructions.
C++ becomes more interesting when compared to languages that don;t provide the level of control, such as Java. This is an entirely object-oriented programming language, with a higher-degree of abstraction (with little or no interaction with the underlying architecture). Rather than producing machine code, Java produces byte code which can be run on any platform that supports the Java Virtual Machine. As such, it is more portable as programs need only be compiled once to run on any platform whereas C++ code must be compiled separately for each platform, and must include code to filter out code that is irrelevant to the current platform. However, since Java programs must run in a virtual machine, they are very much slower than equivalent C++ programs.
C++ is also more interesting in that you aren't restricted to using object-oriented programming principals. You can choose to mix C++ code with C-style code (which is a structured language) and also raw assembly routines, thus making it far more flexible than Java, which is entirely object-oriented.
Although there's little you can't do in C++, that doesn't make it the best language in every situation. For instance, if you have a deadline to meet, C++ might be too complex a language to meet that deadline, thus forcing you to use a more abstract language designed specifically for rapid application development (RAD). For instance, it's often useful to model algorithms and design concepts using a RAD before committing yourself to a more lengthy software development in C++. The feedback from the RAD can, in fact, reduce the overall development cycle as the models can often be incorporated into the final design with only minimal or trivial modification.
However, C++ comes into its own when high-performance is the main criteria, and raw Assembly Language would be far too costly to implement in a reasonable time-frame. Modern compilers can optimise the machine code in much the same way an Assembly Language programmer exploits hardware features to produce highly-efficient code, but there's often room for further improvement. However, C++ is flexible enough to allow the programmer to make these adjustments by hand. And, for me, that's where things can get really interesting.
What are the similarities between if else and switch case in c program?
A switch-case statement is used to select between multiple values for a single variable. Like having a case for 1 2 and 3 for an integer.
An If-else statement is used for evaluating an expression to either true or false.
C program to find whether an integer array is a palindrome?
C Program to Find Given Number is palindrome or Not palindrome . #include<stdio.h> #include<conio.h> void main() { int rev,num,r1,r2,r3; clrscr(); printf("/n enter values for num"); scanf("%d",&num); r1=num%10; num=num/10; r2=num%10; num=num/10; r3=num; rev=(r1*100)+(r2*10)+(r3*1); if(num==rev) { printf("entre number is palindrome number"); } else { printf("enter number is not palindrome number"); } getch(); }
top pointer of a stack is the pointer that refers to the top most element of the stack.
Syntax errors are spelling mistakes or incorrect markup within the code.
E.g.
In c, the following is correct:
int a;
However, the following are all examples of syntax errors:
inta ;
itn a;
int a
C program to solve equation in runge kutta method?
PROGRAM :-
/* Runge Kutta for a set of first order differential equations */
#include
#include
#define N 2 /* number of first order equations */
#define dist 0.1 /* stepsize in t*/
#define MAX 30.0 /* max for t */
FILE *output; /* internal filename */
void runge4(double x, double y[], double step); /* Runge-Kutta function */
double f(double x, double y[], int i); /* function for derivatives */
void main()
{
double t, y[N];
int j;
output=fopen("osc.dat", "w"); /* external filename */
y[0]=1.0; /* initial position */
y[1]=0.0; /* initial velocity */
fprintf(output, "0\t%f\n", y[0]);
for (j=1; j*dist<=MAX ;j++) /* time loop */
{
t=j*dist;
runge4(t, y, dist);
fprintf(output, "%f\t%f\n", t, y[0]);
}
fclose(output);
}
void runge4(double x, double y[], double step)
{
double h=step/2.0, /* the midpoint */
t1[N], t2[N], t3[N], /* temporary storage arrays */
k1[N], k2[N], k3[N],k4[N]; /* for Runge-Kutta */
int i;
for (i=0;i
{
t1[i]=y[i]+0.5*(k1[i]=step*f(x,y,i));
}
for (i=0;i
{
t2[i]=y[i]+0.5*(k2[i]=step*f(x+h, t1, i));
}
for (i=0;i
{
t3[i]=y[i]+ (k3[i]=step*f(x+h, t2, i));
}
for (i=0;i
{
k4[i]= step*f(x+step, t3, i);
}
for (i=0;i
{
y[i]+=(k1[i]+2*k2[i]+2*k3[i]+k4[i])/6.0;
}
}
double f(double x, double y[], int i)
{
if (i==0)
x=y[1]; /* derivative of first equation */
if (i==1)
x= -0.2*y[1]-y[0]; /* derivative of second equation */
return x;
}
Design an If-Then statement (or a flowchart with a single alternative decision structure) that assigns 0 to the variable b and assigns 1 to the variable c if the variable a is less than 10.
Design an If-Then-Else statement (or a flowchart with a dual alternative decision structure) that assigns 0 to the variable b if the variable a is less than 10. Otherwise, it should assign 99 to the variable b.
The following pseudocode contains several nested If-Then-Else statements. Unfortunately, it was written without proper alignment and indentation. Rewrite the code and use the proper conventions of alignment and indentation.
If score < 60 Then
Display "Your grade is F."
Else
If score < 70 Then
Display "Your grade is D."
Else
If score < 80 Then
Display "Your grade is C."
Else
If score < 90 Then
Display "Your grade is B."
Else
Display "Your grade is A."
Design nested decision structures that perform the following: If amount1 is greater than 10 and amount2 is less than 100, display the greater of amount1 and amount2.
Rewrite the following If-Then-Else If statement as a Select Case statement.
If selection == 1 Then
Display "You selected A."
Else If selection == 2 Then
Display "You selected 2."
Else If selection == 3 Then
Display "You selected 3."
Else If selection == 4 Then
Display "You selected 4."
Else
Display "Not good with numbers, eh?"
End If
Design an If-Then-Else statement (or a flowchart with a dual alternative decision structure) that displays “Speed is normal” if the speed variable is within the range of 24 to 56. If speed holds a value outside this range, display “Speed is abnormal.”
Design an If-Then-Else statement (or a flowchart with a dual alternative decision structure) that determines whether the points variable is outside the range of 9 to 51. If the variable holds a value outside this range it should display “Invalid points.” Otherwise, it should display “Valid points.”
Design a case structure that tests the month variable and does the following: If the month variable is set to 1, it displays “January has 31 days.”
If the month variable is set to 2, it displays “February has 28 days.”
If the month variable is set to 3, it displays “March has 31 days.”
If the month variable is set to anything else, it displays “Invalid selection.”
minimum is set.
End If
End If
End If
End If
Where does c language program begin execution?
The execution of the program starts with function main, wherever it is in the source.
What are the various data types in C plus plus?
Data types specify how data is interpreted. All data in a binary computer is stored as a sequence of bits (binary digits), thus all data is represented by numeric values. The data type associated with that data determines how many bits the data occupies and how that data should be interpreted. For instance, an unsigned char data type occupies 8 bits (1 byte) which translate to a numeric value in the range 0 to 255. These values map to ASCII character codes in the current code page, thus if you were to output a char data type it would print the character associated with the character code rather than the numeric value of the code. Unicode character codes use 16 bits (2 bytes) to represent each character and are therefore unsigned short types, also known as wchar_t types.
The primitive data types include int, short and char, which are all integral data types used to store integers (whole numbers). Each may be further qualified with the signed or unsigned keywords, thus a signed char will represent values in the range -128 to +127.
Strings of characters are represented as an array of char types, typically terminated by a null character which has the value 0. Arrays are simply sequence containers containing one or more data elements of the same type. Since the length of each element is the same, it is trivial to locate any element within the array given the element's index where the first element can be found at index 0. Thus an array of n elements will have indices in the range 0 to n-1. Knowing the size of each element (as determined by its type) means that element x can be found at the memory address x*sizeof(element) bytes from the start of the array, using nothing more than simple pointer arithmetic. However, when you declare an array, the subscript operator can be used to specify the index of the element you wish to examine, while C++ does the pointer arithmetic in the background.
More complex data types can be declared using class or struct keywords. The declaration of these types determines how they are mapped in memory and ultimately how they are interpreted. Primitive data types act as the building blocks for these complex data types, but more complex data types can be composed from any combination of primitive and pre-existing complex data types to produce ever more highly complex data types.
Instances of a type are known as variables or constants, depending on whether the value of the instance can be changed or not. If the type is a complex data type, such as a class or struct, the instance is known as an object, which can also be variable or constant. Many new users regard classes and objects as being the same thing, however a class is the definition of a type while an object is an instance of the type, in the same way that a char is a type while a char variable is an instance of the type.
How do you write a c function to swap two variables without using a temporary variable?
You can swap values a and b without a temporary as follows:
a=a^b
b=a^b
a=a^b
(^ is the bitwise XOR operator)
To show how this works, let's consider the values a=180 and b=204. In binary, 180 is 10110100 while 204 is 11001100. Thus:
a = 10110100
b = 11001100
a^b means that we look at the corresponding bits in each input value and output a 1 if one and only one of the two input bits is set. Thus the output (o) is:
a = 10110100
b = 11001100
o = 01111000
In the expression a=a^b, the output of a^b is assigned to a, thus the values of a and b now look like this:
a = 01111000
b = 11001100
We then repeat the operation, a^b, this time assigning the output to b:
a = 01111000
b = 11001100
o = 10110100
So now we have:
a = 01111000
b = 10110100
We repeat the operation one more time, assigning the output value to a:
a = 01111000
b = 10110100
0 = 11001100
So now we have:
a = 11001100
b = 10110100
The two values have now been swapped.
To write this in C, we can use shorthand expressions using the compound XOR-ASSIGN operator (^=):
a^=b
b^=a
a^=b
These individual expressions can then be combined into a single expression:
a^=b^=a^=b
Finally, to use this expression in a C function, we need to pass a and b by reference (using pointer variables):
void swap (int* a, int* b) {
(*a)^=(*b)^=(*a)^=(*b);
}
Note that a and b must be of an integral type (char, short, long, int, unsigned, etc). The example above only works on type int. If we wish to swap other types, or more complex types, we must treat those values as if they were an integral type. One way to achieve this is to treat those types as if they were an array of type char, supplying the length of the arrays through a separate argument:
void swap (char* a, char* b, size_t size) {
for (int i=0; i<size; ++i) {
a[i]^=b[i]^=a[i]^=b[i];
}
}
For example, to swap two doubles, we can use the following call:
int main (void) {
double a, b;
a = 3.14;
b = 1.1;
swap ((char*) &a, (char*) &b, sizeof (double));
assert (a==1.1);
assert (b==3.14);
return 0;
}
Note that a and b must of the same type.