Showing posts with label pointer. Show all posts
Showing posts with label pointer. Show all posts

### C Programming Questions and Answers

// a) If a 5 digit number is input through the keyboard, write a program to print the sum.

#include <stdio.h>

int main(){
int number, sum = 0, remainder = 0, counter = 0;
printf("Enter an integer\n");
scanf("%d", &number);
while (number != 0){
remainder = number%10;
counter += 1;
sum += remainder;
number = number/10;
}
if(counter == 5){
printf("Sum of digits of %d.\n", sum);
}
else{
printf("\nIt was not 5 digit number.\n");
}
return 0;
}

// b) If a four digit number is input through the keyboard, write a program to find the sum of first and last digit.

#include <stdio.h>

int main(){
int number, sum = 0, remainder = 0, counter = 0;
printf("Enter an integer\n");
scanf("%d", &number);
while (number != 0){
remainder = number%10;
counter += 1;
if(counter == 1 || counter == 4){
sum += remainder;
}
number = number/10;
}
if(counter == 4){
printf("Sum of digits of %d.\n", sum);
}
else{
printf("\nIt was not 4 digit number.\n");
}
return 0;
}

// e) Write a program to show the advantage of using function in a program.

#include <stdio.h>

int sum(int *arr, int size){
int total = 0;
for(int i = 0; i < size; i++){
total += arr[i];
}
}

int main(){
int number_of_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

int bellow_fifth = 0, all_sum = 0;
bellow_fifth = sum(number_of_array, 5);
all_sum = sum(number_of_array, 10);

printf ("Total of bellow fifth %d\n", bellow_fifth);
printf ("All total in an array %d\n", all_sum);

return 0;
}

// Write a program for the addition of all values from an Array.
#include <stdio.h>

int sum(int *arr, int size){
int total = 0;
for(int i = 0; i < size; i++){
total += arr[i];
}
}

int main(){
int number_of_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

int all_sum = 0;
all_sum = sum(number_of_array, 10);

printf("All total in an array %d\n", all_sum);

return 0;
}

// a) If a 10 digit number is input , write a program to print the sum of all odd digits.

#include <stdio.h>

int main(){
int number, sum = 0, remainder = 0, counter = 0;
printf("Enter an integer\n");
scanf("%d", &number);
while (number != 0){
remainder = number%10;
counter += 1;
if(remainder%2 != 0){
sum += remainder;
}
number = number/10;
}
if(counter == 10){
printf("Sum of odd digits of %d.\n", sum);
}
else{
printf("\nIt was not 10 digit number.\n");
}
return 0;
}

// b) If a four digit number is input through the keyboard, write a program to find the sum of first and last digit.

#include <stdio.h>

int main(){
int number, sum = 0, remainder = 0, counter = 0;
printf("Enter an integer\n");
scanf("%d", &number);
while (number != 0){
remainder = number%10;
counter += 1;
if(counter == 1 || counter == 4){
sum += remainder;
}
number = number/10;
}
if(counter == 4){
printf("Sum of digits of %d.\n", sum);
}
else{
printf("\nIt was not 4 digit number.\n");
}
return 0;
}

// e) Write a program to check a prime number between 1 and 100.

#include <stdio.h>
int main(){
for(int i = 1; i < 101; i++){
int flag = 1;
for(int m = 2; m < i; m++){
if(i%m == 0){
flag = 0;
break;
}
}
if(flag == 1){
printf("This is a prime number %d\n", i);
}
}
return 0;
}

// f) Write a program for the addition of all even values from an integer Array.

#include <stdio.h>

int sum(int *arr, int size){
int total = 0;
for(int i = 0; i < size; i++){
if(arr[i]%2 == 0){
total += arr[i];
}
}
}

int main(){
int number_of_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

int all_sum = 0;
all_sum = sum(number_of_array, 10);

printf("All total in an array %d\n", all_sum);

return 0;
}

Do-While :

a do while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given Boolean condition at the end of the block.

Syntax:

do{
statement(s);
}
while (Boolean condition)

Example:
do{
run();
}
while(edge)

While loop:

a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.
Syntax:
`while( Boolean condition) {`
`   statement(s);`
`}`

Example:
while (edge)
{
run();
}

For loop:

for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Syntax:

`for ( init; condition; increment ) {`
`   statement(s);`
`}`

`#include <stdio.h>`
` `
`int main () {`
` `
`   int a;`
`         `
`   /* for loop execution */`
`   for( a = 10; a < 20; a = a + 1 ){`
`      printf("value of a: %d\n", a);`
`   }`
` `
`   return 0;`
`}`

Pointer and Arrays

When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array. Base address i.e address of the first element of the array is also
allocated by the compiler. Suppose we declare an array arr,

int arr = { 1, 2, 3, 4, 5 };

Assuming that the base address of arr is 1000 and each integer requires two bytes, the five
elements will be stored as follows: Here variable arr will give the base address, which is a constant pointer pointing to the first
element of the array, arr. Hence arr contains the address of arr i.e 1000. In short, arr has two purpose - it is the name of the array and it acts as a pointer pointing
towards the first element in the array. arr is equal to &amp;arr by default

We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr;

// or,

p = &amp;arr; //both the statements are equivalent.

Now we can access every element of the array arrusing p++ to move from one element to
another

Switch :

switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

## Syntax

The syntax for a switch statement in C programming language is as follows −
`switch(expression) {`
` `
`   case constant-expression  :`
`      statement(s);`
`      break; /* optional */`
`         `
`   case constant-expression  :`
`      statement(s);`
`      break; /* optional */`
`  `
`   /* you can have any number of case statements */`
`   default : /* Optional */`
`   statement(s);`
`}`

`#include <stdio.h>`
` `
`int main () {`
` `
`   /* local variable definition */`
`   char grade = 'B';`
` `
`   switch(grade) {`
`      case 'A' :`
`         printf("Excellent!\n" );`
`         break;`
`      case 'B' :`
`      case 'C' :`
`         printf("Well done\n" );`
`         break;`
`      case 'D' :`
`         printf("You passed\n" );`
`         break;`
`      case 'F' :`
`         printf("Better try again\n" );`
`         break;`
`      default :`
`         printf("Invalid grade\n" );`
`   }`
`   `
`   printf("Your grade is  %c\n", grade );`
` `
`   return 0;`
`}`

Go-to:

goto statement in C programming provides an unconditional jump from the 'goto' to a labeled statement in the same function

## Syntax

The syntax for a goto statement in C is as follows −
`goto label;`
`..`
`.`
`label: statement;`

`#include <stdio.h>`
` `
`int main () {`
` `
`   /* local variable definition */`
`   int a = 10;`
` `
`   /* do loop execution */`
`   LOOP:do {`
`   `
`      if( a == 15) {`
`         /* skip the iteration */`
`         a = a + 1;`
`         goto LOOP;`
`      }`
`                 `
`      printf("value of a: %d\n", a);`
`      a++;`
` `
`   }while( a < 20 );`
` `
`   return 0;`
`}`

C File I/O

A file represents a sequence of bytes, regardless of it being a text file or a binary file. C programming language provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices. This chapter will take you through the important calls for file management.

## Opening Files

You can use the fopen( ) function to create a new file or to open an existing file. This call will initialize an object of the type FILE, which contains all the information necessary to control the stream. The prototype of this function call is as follows −
`FILE *fopen( const char * filename, const char * mode );`
Here, filename is a string literal, which you will use to name your file, and access mode can have one of the following values −
 Sr.No. Mode & Description 1 r Opens an existing text file for reading purpose. 2 w Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file. 3 a Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content. 4 r+ Opens a text file for both reading and writing. 5 w+ Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist. 6 a+ Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.
If you are going to handle binary files, then you will use following access modes instead of the above mentioned ones −
`"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"`

## Closing a File

To close a file, use the fclose( ) function. The prototype of this function is −
`int fclose( FILE *fp );`
The fclose(-) function returns zero on success, or EOF if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.
There are various functions provided by C standard library to read and write a file, character by character, or in the form of a fixed length string.

## Writing a File

Following is the simplest function to write individual characters to a stream −
`int fputc( int c, FILE *fp );`
The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream −
`int fputs( const char *s, FILE *fp );`
The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file. Try the following example.
Make sure you have /tmp directory available. If it is not, then before proceeding, you must create this directory on your machine.
`#include <stdio.h>`
` `
`main() {`
`   FILE *fp;`
` `
`   fp = fopen("/tmp/test.txt", "w+");`
`   fprintf(fp, "This is testing for fprintf...\n");`
`   fputs("This is testing for fputs...\n", fp);`
`   fclose(fp);`
`}`
When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions. Let us read this file in the next section.

Given below is the simplest function to read a single character from a file −
`int fgetc( FILE * fp );`
The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error, it returns EOF. The following function allows to read a string from a stream −
`char *fgets( char *buf, int n, FILE *fp );`
The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a nullcharacter to terminate the string.
If this function encounters a newline character '\n' or the end of the file EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including the new line character. You can also use int fscanf(FILE *fp, const char *format, ...) function to read strings from a file, but it stops reading after encountering the first space character.
`#include <stdio.h>`
` `
`main() {`
` `
`   FILE *fp;`
`   char buff;`
` `
`   fp = fopen("/tmp/test.txt", "r");`
`   fscanf(fp, "%s", buff);`
`   printf("1 : %s\n", buff );`
` `
`   fgets(buff, 255, (FILE*)fp);`
`   printf("2: %s\n", buff );`
`   `
`   fgets(buff, 255, (FILE*)fp);`
`   printf("3: %s\n", buff );`
`   fclose(fp);`
` `
`}`
When the above code is compiled and executed, it reads the file created in the previous section and produces the following result −
`1 : This`
`2: is testing for fprintf...`
` `
`3: This is testing for fputs...`