answersLogoWhite

0

📱

C Programming

Questions related to the C Computer Programming Language. This ranges all the way from K&R to the most recent ANSI incarnations. C has become one of the most popular languages today, and has been used to write all sorts of things for nearly all of the modern operating systems and applications. It it a good compromise between speed, power, and complexity.

9,649 Questions

Program to check whether a number is a palindrome or not using functions?

There are several ways to determine if a string is a palindrome or not. Typically, you must first ignore all spacing, capitalisation and punctutation within the string, which can be done by copying the string, character by character, ignoring all non-alphanumeric characters. You then point to the first and last characters in the modified string and, so long as both characters under the pointers are the same, work the pointers towards the middle of the string until the pointers either meet in the middle or they pass each other. That is, if the string has an odd count of characters, the pointers will meet at the middle character, otherwise they will pass each other. At that point you can say with certainty the string is a palindrome. If the characters under the pointers differ at any time, then the string is not a palindrome. This is fairly straightforward to program.

A more interesting problem is when you have to locate the longest palindrome within a string which is not itself a palindrome. For instance, the string "Madam, I'm Adam is a palindrome" is not a palindrome, but it does contain one: "Madam I'm Adam". In this case we cannot point to the first and last characters and work towards the middle. Instead, we have to test every possible substring of the string. We do this by starting at the first character and treat it as if it were actually the middle character of a palindrome, and then move our pointers to the left and right of this character while the characters match. When they no longer match, or one of the pointers has reached either end of the string, we store the longest palindrome found up to that point and then move onto the next character and treat it as the middle character. If we continue in this manner, treating every character as if it were the middle character of a palindrome, we will eventually locate the longest palindrome.

The problem with this approach is when the longest palindrome has an even number of characters instead of an odd number. To get around this we simply place a single space between each character, and treat each of those as being the middle character as well. When a palindrome is found, we simply remove the spaces. In this way we can use exactly the same algorithm to cater for both odd and even character palindromes.

The only remaining problem is when we wish to print the palindrome itself. Since this will be a substring of the original string, we cannot use the modified string we used to locate the palindrome. One way to get around that is to store the original positions of each letter in an array of indices, and use that array to determine where the substring lies with in the original string.

The following program demonstrates this technique in full. The key function is the ispalindrome() function, which accepts a lower-case copy of the string (including the original spacing an punctuation), and a vector that contains the indices of each letter within the string (ignoring puctuation and spacing), separated by -1 values (representing the implied spaces between each letter). The pos value tells the function which index of the vector is to be treated as the middle character of the potential palindrome, while x and y are output parameters that determine the start and end of the palindrome within the vector. The function returns true if a palindrome was found, and the x and y values can be used to extract the palindrome from the original string, using the indices stored in the vector. Note that when the search for a palindrome fails, we step back the x and y indices by one, and if the vector index is -1, then we step back another index. We then test the x and y values to see if they indicate a palindrome was found or not.

The strip() function is another key function. This generates the vector from the lower case copy of the original string. Although we could eliminate the -1 values at the start and end of the vector, it's simpler to just leave them in.

You will note that the program can cater for strings that are themselves palindromes, as well as strings that contain palindromes.

#include<iostream>

#include<string>

#include<vector>

using namespace std;

string input_string(string prompt)

{

cout<<prompt<<":\t";

string input;

getline(cin, input, '\n');

return(input);

}

void convert_tolower(string& s)

{

for(string::iterator i=s.begin(); i!=s.end(); ++i)

*i=tolower(*i);

}

vector<int> strip(const string& s)

{

vector<int> v;

v.push_back(-1);

for(int i=0; i<s.size(); ++i)

{

if((s[i]>='a' && s[i]<='z') (s[i]>='0' && s[i]<='9'))

{

v.push_back(i);

v.push_back(-1);

}

}

return(v);

}

bool ispalindrome(const string s, const vector<int> v, int pos, int& x, int& y)

{

for(x=pos,y=pos; x>=0 && y<v.size(); --x, ++y)

if( v[x]!=-1 && ( s[v[x]]!=s[v[y]] ))

break;

++x, --y;

if( v[x]==-1 )

++x, --y;

return(x>=0 && x<y && y-x>1);

}

int main()

{

string input;

while(1)

{

input=input_string("Enter a string");

if(input.size()==0)

break;

string copy(input);

convert_tolower(copy);

vector<int> v=strip(copy);

string pal;

int pos=0;

for(int i=0; i<v.size(); ++i)

{

int start=0, end=0;

if( ispalindrome( copy, v, i, start, end))

{

string tmp( input.substr(v[start],v[end]-v[start]+1));

if( tmp.size() > pal.size() )

{

pal = tmp;

pos = v[start];

}

}

}

if( pal.size() )

{

cout<<"Palindrome:\t";

for(int i=0; i<pos; ++i)

cout<<" ";

cout<<pal<<"\n"<<endl;

}

else

cout<<"The string contains no palindromes!\n"<<endl;

}

return(0);

}

Example output:

Enter a string: Madam, I'm Adam

Palindrome: Madam, I'm Adam

Enter a string: Madam, I'm Adam is a palindrome

Palindrome: Madam, I'm Adam

Enter a string: In girum imus nocte et consumimur igni

Palindrome: In girum imus nocte et consumimur igni

Enter a string: 0123456765432

Palindrome: 23456765432

Enter a string:

Press any key to continue . . .

Sample text color in C language?

printf("%c[%d;%dmHello World%c[%dm\n",27,1,33,27,0);

What is the language processor?

Language processors are language translation software like assembler, interpreter and compiler

Why is it important to have a solid background in mathematics for programming languages?

You need to to know some basic math to live. right? Likewise you need to know some basic math to start computer programming....beginners start out by learning to do programs like solving a quadratic equation....if you are not thorough with algebra, u can't do it. The way you think is more important.....rather than being good in math, computer programmers are required to think the way math people think - vey very very logically.

Write a c plus plus program to demonstrate call by value and call by reference?

#include<iostream>

void byval(int y)

{

std::cout<<"byval: &y="<<&y<<std::endl;

}

void byref(int& z)

{

std::cout<<"byref: &z="<<&z<<std::endl;

}

int main()

{

int x=42;

std::cout<<"main : &x="<<&x<<std::endl;

byval(x);

byref(x);

return(0);

}

Example output:

main : &x=001DF800

byval: &y=001DF72C

byref: &z=001DF800

When you pass by value, the y argument has a different memory address to that of x. In other words, y is a copy of x (you pass the value of x, not x itself). Thus any changes made to y will have no affect upon x. Often this is desirable, but note that when passing a complex object by value, you will automatically invoke the object's copy constructor, which is often unnecessary. Pass by value should only be used when the function needs to modify the argument's value, but without affecting the argument that was passed.

When you pass by reference, the z argument has the same address as x. Thus z refers to x. In other words, z is an alias, an alternate name, for x, thus any changes made to the value of z will also change the value of x, since they are one and the same variable. If the function does not actually need to alter the value of the reference, then the reference should be declared constant. This assures the caller that the object's immutable members will not be altered by the function.

Note that you can also achieve pass by reference by passing a pointer to the variable. Pointers are always passed by value, thus the pointer will actually be a copy of the pointer you pass, but both pointers will still refer to the same memory address, thus the net effect is a pass by reference. However, if a pointer is guaranteed to be non-NULL, then it is more efficient to pass the address being pointed at by reference, since references can never be NULL (a NULL reference will invalidate your program).

To pass a pointer by reference, you need to add an extra level of indirection. Thus when passing a pointer to an int (int*), you need to pass a pointer to a pointer to int instead (int**). The pointer to pointer is passed by value, but the pointer to int is effectively passed by reference, thus allowing you to change the value of both the pointer and also what it is pointing at (unless one, the other, or both, are declared const).

A multithreaded program that generates the Fibonacci series using Pthreads?

#include<stdio.h>

#include<time.h>

#include<pthread.h>

#include<stdlib.h>

#include<sys/types.h> /* need to calculate which I will implement later */

void *fibr(void *n);

void *fibr_1(void *k);

signed long long int fibonacci(signed long long int);

int main(){

clock_t begin, end;

double time_spent;

pthread_t tid,tid1;

int result,result1;

signed long long int n=6;

signed long long int m=7;

result=pthread_create(&tid,NULL,fibr,&n);

if(result){

perror("pthread_create");

return 1;

}

result1=pthread_create(&tid1,NULL,fibr,&m);

if(result1){

perror("pthread_create");

return 1;

}

if(pthread_join(tid,NULL)){

perror("pthread_join");

return 1;

}

if(pthread_join(tid1,NULL)){

perror("pthread_join");

return 1;

}

printf("Fib value=%lld\n",n+m);

pthread_exit(NULL);

}

void *fibr(void *n){

signed long long int *y=n;

signed long long int x=*y;

pthread_t tid2,tid3;

signed long long int i,j;

/* How do I assign values to i , j in order to

achieve the level viz fib(n-2)....fib(n-4) */

if(pthread_create(&tid2,NULL,fibr_1,&i))

{

perror("pthread_create");

}

if(pthread_create(&tid3,NULL,fibr_1,&j))

{

perror("pthread_create");

}

if(pthread_join(tid2,NULL))

{

perror("pthread_join");

}

if(pthread_join(tid3,NULL))

{

perror("pthread_join");

}

/* How to return the values of i, j combined with *y . if I do *y+i+j, the result

is not coming correctly */

*y=fibonacci(x);

return NULL;

}

void *fibr_1(void *k){

long long int *a=k;

long long int b=*a;

*a=fibonacci(b);

return NULL;

}

signed long long int fibonacci(signed long long int x){

if((x==0)(x==1))

return x;

return fibonacci(x-1)+fibonacci(x-2);

}

Implement Bresenham algorithm using c language?

#include<stdio.h> #include<conio.h> #include<math.h> #include<graphics.h> void draw_line(float,float,float,float); main() { int driver,mode; float x1,y1,x2,y2; clrscr(); printf("Enter the two endpoints of the line:"); printf("\nx1 ="); scanf("%f",&x1); printf("y1 ="); scanf("%f",&y1); printf("x2 ="); scanf("%f",&x2); printf("y2 ="); scanf("%f",&y2); clrscr(); driver = DETECT; initgraph(&driver,&mode,"\\tc\\bgi"); \\path of bgi can be different in your case draw_line(x1,y1,x2,y2); getch(); closegraph(); } void draw_line(float x1,float y1,float x2,float y2) { float dy,dx; float x,y; float p,p0,dp1,dp2; dy = y2-y1; dx = x2-x1; p0 = 2 * (dy - dx); dp1 = 2 * dy; dp2 = 2 * (dy - dx); putpixel(x1,y1,EGA_WHITE); p = p0; for(x=x1+1,y=y1;x<x2;x++) { if(p < 0) { p = p+dp1; putpixel(x,y,EGA_WHITE); } else { p = p+dp2; y++; putpixel(x,y,EGA_WHITE); } }

Can function return more than one value?


Strictly speaking, only one.

However, a trick many programmers use is to have the function create "side effects" by changing the value of its arguments as well as returning a value. A pseudocode example might be something like a file-existence checker. It would be a boolean function that returns TRUE if the file exists and FALSE if it doesn't. However, depending on the language used it could also modify its arguments so they provided the file's size and record type if it exists. For example: if bFileExists (cFileName, iFileSize, iRecType) then {do something with iFileSize ...}


C program to read a text and count occurrence of a particular word?

#include<stdio.h>

main()

{

int i,words,spaces;

char a[30];

printf("enter the string") ;

scanf("%s",a);

for(i=0;a[0]!="\0";i++)

{

if (a[i]=' ')

spaces++;

}

printf("the no. of spaces in the string is %d",spaces);

printf("the number of words in the string is %d",spaces+1);

}

Program for dequeue in data structure?

Display function in de queue

void display()

{

int i;

if((front == -1) (front==rear+1))

printf("\n\nQueue is empty.\n");

else

{

printf("\n\n");

for(i=front; i<=rear; i++)

printf("\t%d",queue[i]);

}

}

What are nested structures?

Nested structures means we can have a structure inside another

eg:

struct A

{

...........

............

struct B

{

........

........

}b;

}a;

What is operator associativity in C?

Operator

Description

Associativity

()
[]
.
->
++ -- Parentheses (function call) (see Note 1)
Brackets (array subscript)
Member selection via object name
Member selection via pointer
Postfix increment/decrement (see Note 2)

left-to-right

++ --
+ -
! ~
(type)
*
&
sizeof Prefix increment/decrement
Unary plus/minus
Logical negation/bitwise complement
Cast (change type)
Dereference
Address
Determine size in bytes right-to-left * / % Multiplication/division/modulus left-to-right + - Addition/subtraction left-to-right << >> Bitwise shift left, Bitwise shift right left-to-right < <=
> >= Relational less than/less than or equal to
Relational greater than/greater than or equal to left-to-right == != Relational is equal to/is not equal to left-to-right & Bitwise AND left-to-right ^ Bitwise exclusive OR left-to-right | Bitwise inclusive OR left-to-right && Logical AND left-to-right Logical OR left-to-right ?: Ternary conditional right-to-left =
+= -=
*= /=
%= &=
^= |=
<<= >>= Assignment
Addition/subtraction assignment
Multiplication/division assignment
Modulus/bitwise AND assignment
Bitwise exclusive/inclusive OR assignment
Bitwise shift left/right assignment right-to-left

,

Comma (separate expressions) left-to-right

Write a program to accept two numbers and display their sum?

Assuming you're using the C programming language (as you did not specify any other), and that you're making some sort of arithmetic tester, a simple answer would be:

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

int main()

{

time_t seconds;

time(&seconds);

srand((unsigned int)seconds);

int num1 = (rand()%100);

int num2 = (rand()%100);

int sum = num1 + num2;

int ans;

printf("What is %d + %d? ", num1, num2);

scanf("%d", &ans);

if(ans == sum) printf("Correct!");

else printf("Wrong, correct answer is %d", sum);

return 0;

}

Write a qbasic program to display the multiplication tables from 1 to 10?

Writing this QBASIC code purely on the fly...; without actually testing out if it works/or, not...

CLS

FOR tablesNo%=1 TO 10

FOR timesNo%=1 TO 10

PRINT timesNo%*tablesNo%; " ";

NEXT

PRINT

NEXT

END

NOTE: The numbers are not yet formatted to line up perfectly straight with one another.

Why do local variables lose their values between calls to the function in which they are defined?

They are designed to work that way - and it's actually quite useful to have variables that work that way. If you want to keep a value from one method call to the next, you have to use some other way to store the information. For example, you can store information in an object field.

Write a test program that prints a 3 by 3 matrix?

4.(Displaying matrix of 0s and 1s ) write a method that displays by n by n matrix using the following header : Public static void printMatrix(int n) Each element is o or 1,which is generated randomely. Write a test program that prints a 3 by 3 matrix that may look like this: 010 000 111 4.(Displaying matrix of 0s and 1s ) write a method that displays by n by n matrix using the following header : Public static void printMatrix(int n) Each element is o or 1,which is generated randomely. Write a test program that prints a 3 by 3 matrix that may look like this: 010 000 111

What does printf and scanf return?

Printf returned no. of character receive .

scanf return no of variable to be inputed according to format specifier . eg:

i=printf("thisisc") printf("%d",i); //i=7 j=scanf("dd",&a,&b,&c,&d); printf("%d",j);

IT IS MOST APPROPRIATE ANSWER FOR THIS Q .......... PLZ DO Practically............

What are basic features of c?

The C programming model is that the programmer knows exactly what they want to do and how to use the language constructs to achieve that goal. The language lets the expert programmer express what they want in the minimum time by staying out of their .

How are break points set using c plus plus?

Break points are a feature of the debugger and is implementation specific. For instance, in Visual C++, you place the cursor at the line where you want the breakpoint to be and hit the F9 key to toggle it on and off. When enabled, you can set the properties of the breakpoint, such as what condition(s) must be true in order for the program to break at that point.

What is the difference between a queue and a stack?

Queue is better than stack because jobs in a queue are processed on a first in first out order thereby reducing traffic and delay.

But jobs in a stack are processed in a last in first out order causing traffic and delay of jobs that arrived earlier

Give sample program?

class firstprog

{

public static void main (String args[])

{

System.out.pritnln("My first Program in Java ");

}

}

Simple Java Programe

Write the above program in Ms dos's edit or Notepad of Windows save it with "firstprog.java" run the commands given below in command prompt of Ms Dos to get the output Remamber Java is case sensative so mentain capital and small letter.

1. javac firstprog.java

2. java firstprog

What is main different between do while and while?

If you want to execute a statement which is in while loop at least one time you can use do- while loop.

this is why because initially first statements will be executed then condition will be checked. but in case of while first condition will be check then statements will be executed

Write a c programme to check whether given number is Fibonacci?

#include<iostream.h>

#include<conio.h>

void main()

{

long int n,a=0,b=1;

cout<<"dear user Enter number as u wish";

cin>>n;

while(n>0)

{

c=a+b;

cout<<"c<<"\t\t";

a=b;

b=c;

}

getch();

}

Can you merge nested for loop in one loop?

Yes, sometimes it is possible. It depends on what the nested loop actually does of course, but there are cases where a single loop can achieve the same end.

For instance, the following nested loop prints the product of each pair of values in the range 1 to 10:

for( int x=1; x<=10; ++x )

for( int y=1; y<=10; ++y )

printf( "%d * %d = %d\r\n", x, y, x*y );

This could be written as a single loop:

for( int z=0; z<100; ++z )

{

int x = z/10+1;

int y = z%10+1;

printf( "%d * %d = %d\r\n", x, y, x*y );

}

Note that the nested loop is easier to read and maintain and is also much more efficient than the merged loop.