Wednesday, October 31, 2018

C String - Predict output- Answer


Predict Program Output Based on C String


Output of following C Programs are not very simple. These are simple but very interesting top c programs based on C Strings asked during viva and interviews.

Program-1


#include <stdio.h> 
int main () 

    char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
    printf("Greeting message: %s\n", greeting ); 
    return 0; 
}

Output: Greeting message: Hello
Justification: Variable greetings will be initialized at compile time. '\0' is end of string character, and will not be printed along with Hello.


Program-2

#include "stdio.h" 
int main() 

    char str[] = { 'A', 'B', 'C', 'D' }; 
    char *p = &str[1]; 
    *p++;
    printf("%c ", *p);
    *p++;
    printf("%c ", *p);


Output: C D
Justification: Memory address of str[1] will be assigned to character pointer (*p). The value stored ar str[1] is 'B'. Statement *p++ will increment its value by one; which results in value 'C' which is printed. Again *p++ will increment its value by one; which results in 'D' which is printed resulting in final output as C D



Program-3


#include<stdio.h>
#include<string.h>
int main()
{
    char str1[20] = "C Program";
    char str2[20] = "C Practicals";
    printf("%s\n", strcpy(strcat(str1, str2), str2));
    return 0;
}

Output: C Practicals
Justification: Inner function strcat will be executed first, which will append the str2 (i.e. C Practicals) into str1 variable. Then, str2 (i.e. C Practicals) will be copied to str1; which will be the final output printed on screen.


Program-4


#include<stdio.h>
#include<string.h>
int main()
{
    printf("%d", strlen("01234567"));
    return 0;
}

Output: 8
Justification: strlen() function find the length of "01234567" which will be printed on screen.


Program-5


#include<stdio.h>
int main()
{
    printf(10 + "C Program Practicals");
    return 0;
}

Output: Practicals
Justification: First 10 characters will be ignored while printing a string "C Program Practicals"; hence output is Practicals.


Sunday, October 28, 2018

C String - Predict output


Predict Program Output Based on C String


Output of following C Programs are not very simple. These are simple but very interesting top c programs based on C Strings asked during viva and interviews.


Program-1


#include <stdio.h> 
int main () 

    char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
    printf("Greeting message: %s\n", greeting ); 
    return 0; 
}

Program-2


#include "stdio.h" 
int main() 

    char str[] = { 'A', 'B', 'C', 'D' }; 
    char *p = &str[1]; 
    *p++;
    printf("%c ", *p);
    *p++;
    printf("%c ", *p);


Program-3


#include<stdio.h>
#include<string.h>
int main()
{
    char str1[20] = "C Program";
    char str2[20] = "C Practicals";
    printf("%s\n", strcpy(strcat(str1, str2), str2));
    return 0;
}

Program-4


#include<stdio.h>
#include<string.h>
int main()
{
    printf("%d", strlen("01234567"));
    return 0;
}


Program-5


#include<stdio.h>
int main()
{
    printf(10 + "C Program Practicals");
    return 0;
}

Click here to check ANSWER

Read more interesting programs at C Program Practicals - Question Bank.


Friday, October 26, 2018

C Pointers - Predict output


Predict Program Output Based on C Pointers

Output of following C Programs are not very simple. These are simple but very interesting top c programs asked during viva and interviews.


Program-1


#include<stdio.h> 
int main() 

    int x = 10, *y, *z; 
    y = &x;  
    z = y; 
    printf("%d, %d, %d", x, *y, *z); 
    return 0; 
}

Program-2

#include "stdio.h" 
int main() 

    char str[] = { 'A', 'B', 'C', 'D' }; 
    char *p = &str[0]; 
    *p++;
    printf("%c ", *p);
    *p++;
    printf("%c ", *p);


Program-3

#include "stdio.h" 
int main() 

    int marks[] = { 50, 60, 70, 80 }; 
    int *p = &marks[0]; 
    *p++;
    printf("%d ", *p);
    *p = *p+2;
    printf("%d ", *p);


Program-4

#include <stdio.h>
int main() 

    int marks[] = { 50, 60, 70, 80 }; 
    int *p = &marks[0]; 
    *p++;
    printf("%d ", *p);
    *p++;
printf("%d ", *p);



Program-5

#include <stdio.h> 
int main() 

    int *ptr; 
    *ptr = 5; 
    printf("%d", *ptr); 
    return 0; 
}

Check your Answer here... 

Thursday, October 25, 2018

Updating File Data using fseek


File Management - Updating File Records


Following program will allow us to change marks of roll no. 101 using fseek() function. Content of "student.txt" (RollNo, Marks, Name) file is as under:

101 50 AAA
102 60 BBB
103 65 CCC

#include <stdio.h>

int main () {
   FILE *fp;
   char str[80];
   int newmarks;
   
   fp = fopen("student.txt","r+");

   printf("Original File Data:\n");
   while(fgets(str,80,fp)!=NULL)
    printf("%s", str);
   //getch();
   
   printf("\n\nEnter new marks of Roll no. 101:");
   scanf("%d", &newmarks);
      
   printf("Updated File Data:\n\n");
   
   itoa(newmarks,str, 10); //convert int into string because fputs function write "string" to fp
   
   fseek(fp, 4, 0); //set the pointer to position no. 4
   
   fputs(str, fp);  //write string to current position of fp
   fclose(fp);
   
   fp = fopen("student.txt","r");

   while(fgets(str,80,fp)!=NULL)
    printf("%s", str);
   
   fclose(fp);
   getch();
   return(0);
}


Output of Program

Original File Data:
101 55 AAA
102 60 BBB
103 65 CCC

Enter new marks of Roll no. 101:75

Updated File Data:
101 75 AAA
102 60 BBB
103 65 CCC

Monday, October 22, 2018

Login Check Function


User Authentication (Login Check Function)

This C program will check the User ID and Password entered by user with the UserID and Password stored into login.txt file. Each line of login.txt contains UserID Password of one user. 

Sample login.txt file contains data of 5 users which are as under:

101 abc123
102 guest
103 hi
guest guest
admin admin

Make sure that each user ID and Password is separated by space.

#include<stdio.h>

int Login_check(char id[], char pass[]);

int main()
{
 int check=0;
 char id[20], pass[20];
 printf("Enter your User ID:");
 scanf("%s", id);

 printf("Enter your Password:");
 scanf("%s", pass);

 check = Login_check(id, pass);

 if (check==1)
   printf("\nLogin successful...\n\nDisplay Menu Here...\n");
   //write main program logic here...  
 else
   printf("\nLogin failed. Try again...\n");

 return 0;
}

int Login_check(char id[], char pass[])
{
 FILE *fp;
 char *fid, *fpass, *token;
 int check=0;
 const char str[40] = "", s[2] = " ";

 fp = fopen("login.txt", "r");

 if(fp==NULL) 
 {
   printf("File error..."); exit(0);
 }
 while(fgets(str, 40, fp)!=NULL)
 {
   fid = strtok(str,s);
   fpass = strtok(NULL,s);
   fpass[strlen(fpass)-1]='\0';

   if((strcmp(id,fid) == 0) && (strcmp(pass,fpass) == 0 ))
   {
     check=1;
   }
 }
 return check;
}

Output of Program

Enter your User ID:guest
Enter your Password:guest

Login successful...

Display Menu Here...


Using realloc function

Dynamic memory management - realloc () function

#include <stdio.h>
#include <stdlib.h>

int main () 
{
   char *str;

   /*memory allocation using malloc()*/
   str = (char *) malloc(7);
   
   strcpy(str, "Gujarat");
   printf("Original String = %s\n\n", str);

   /* Reallocating memory using realloc()*/
   str = (char *) realloc(str, 25);
   printf("Reallocation done...\n\n");
   strcat(str, ", India");
   printf("Updated String = %s", str);

   free(str);
   return(0);
}

Output of Program

Original String = Gujarat

Reallocation done...

Updated String = Gujarat, India

Dynamic memory allocation using calloc


Using calloc() function in C

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i, n;
    int *myspace;

    printf("Enter total numbers to be stored: ");
    scanf("%d", &n);
    
    /*Following statement will allot n blocks of int in memory.
      malloc returns a void pointer; then it is type-casted to (int*).
      myspace points to the first block of the newly allocated space.
    */
  myspace = (int*) calloc(n, sizeof(int)); 
    
    //It returns NULL pointer, if fails to allocate enough space.
    if(myspace == NULL) 
  {
        printf("Error!!! Space problem..");  exit(0);
    }
    //Logic to store numbers into the dynamically allocated space
    for(i=0; i<n; i++)
    {
       printf("Enter number %d:",i+1);
  scanf("%d", myspace+i);
    }
    //Logic to print numbers from dynamically allocated space
    printf("\n%d numbers stored into dynamically allotted space:\n", n);
  for(i=0; i<n; i++) 
  {
    printf("%d ", *(myspace+i));
    }
    return 0;
}


Output of Program

Enter total numbers to be stored: 5
Enter number 1:1
Enter number 2:3
Enter number 3:5
Enter number 4:7
Enter number 5:9

5 numbers stored into dynamically allotted space:
1 3 5 7 9

Sunday, October 21, 2018

Dynamic memory allocation using malloc


malloc() - Dynamic memory allocation function


The process of allocating memory at program run time is known as dynamic memory allocation. Following program will dynamically allot space as per user requirement.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i, n;
    int *myspace;

    printf("Enter total numbers to be stored: ");
    scanf("%d", &n);
    
    /*Following statement will allot n blocks of int in memory.
      malloc returns a void pointer; then it is type-casted to (int*).
      myspace points to the first block of the newly allocated space.
    */
    myspace = (int*) malloc(n*sizeof(int)); 
    
    //It returns NULL pointer, if fails to allocate enough space.
    if(myspace == NULL) 
    {
        printf("Error!!! Space problem..");
        exit(0);
    }
    //Logic to store numbers to dynamically allocated space
    for(i=0; i<n; i++)
    {
       printf("Enter number %d:",i+1);
       scanf("%d", myspace+i); 
    }
    //Logic to print numbers from dynamically allocated space
    printf("\n%d numbers stored in dynamically allotted space:\n", n);
    for(i=0; i<n; i++) 
    {
    printf("%d ", *(myspace+i));
    }
    return 0;
}


Output of program

Enter total numbers to be stored: 5
Enter number 1:2
Enter number 2:4
Enter number 3:6
Enter number 4:8
Enter number 5:10

5 numbers stored in dynamically allotted space:
2 4 6 8 10

Friday, October 19, 2018

Command Line Arguments - Add numbers

Command Line Arguments

Following C program will Add two numbers passed as Command Line Arguments .
[Note: This program is saved with filename: "addnumbers.c" in C: drive.]

#include <stdio.h>

int main( int argc, char *argv[] )  
{
int n1, n2;

  n1 = atoi(argv[1]);
  n2 = atoi(argv[2]);

  if( argc != 3 ) 
{
    printf("Pl. enter three arguments..\n");
  }
  else
    printf("%d", n1+n2);

  return 0;
}

Output of program [Run this program from Command Prompt of your system]

C:\addnumbers 5 5
Total = 10


Friday, October 12, 2018

Time difference using System Date and Time


Following C program will detect the time difference between two time intervals using System Date and Time function.

#include <stdio.h>
#include <time.h>

int main()
{
time_t t1, t2;

time(&t1);
printf("Time reading 1: \nSystem date and time is: %s\n",ctime(&t1));

printf("Wait for a moment...\nPress any key to continue....\n\n");
getch();

//Program logic.....

time(&t2);
printf("Time reading 2:\nSystem date and time is: %s\n\n",ctime(&t2));
   
printf("The time difference = %d sec. ", t2-t1);

return 0;
}


Output of Program

Time reading 1:
System date and time is: Fri Oct 12 10:39:45 2018

Wait for a moment...
Press any key to continue....

Time reading 2:
System date and time is: Fri Oct 12 10:39:48 2018

The time difference = 3 sec.

Sunday, October 7, 2018

Graphical Report - Project Demo


Project Demonstration - Graphical Reports 

This project shows how to generate Graphical Reports of Student's Class Test from "classtest.txt" data file without use of <graphics.h>. 

Assume classtest.txt file contains RollNo and MarksObtained by the students. This program will display horizontal BAR chart of the Marks obtained by the students.

#include<stdio.h>
int main()
{
  FILE *fp;
  int marks, i;
  const char str[80], s[2]=" ";
  char *token;

  fp = fopen("classtest.txt","r");

  if(fp == NULL) { printf("File error.."); exit(0); }

  system("color A1");
  printf("  Class Test Graphical Report(2018)\n");
  printf("=====================================\n");
  printf(" Roll No.| Marks Obtained (Out of 20)\n");
  printf("=====================================\n");

  while(fgets(str,80,fp)!=NULL)
  {
token = strtok(str,s);
printf("     %s   | ", token);
token = strtok(NULL, s);
marks = atoi(token);
for(i=0; i<marks; i++)
  printf("%c", 254);
printf(" %d\n", marks);
  }
  fclose(fp);
  return 0;    
}

Output of Program

Project Demonstration - Graphical Report of Student Class Test

Check more interesting projects here..


Friday, October 5, 2018

Colors in C Project


Using Colors in C Project

Following C code demonstrates how to use Colors in C program without using <graphics.h>.

#include<stdio.h>

int main()
{
  int i;
  printf("\n\n\n");
  for(i=0;i<10;i++)
  {
     system("color B1");
     printf("%c ",254);
  }
  printf("\n\n MAIN MENU \n\n");
  for(i=0;i<10;i++)
  {
      system("color A1");
      printf("%c ",254);
  }
  return 0;    
}

Output of program
Colors in C Program
Adding Colors to C Program

Monday, October 1, 2018

Reading Structure from file

Following program will read a Structure (customer) data from a Customer data file.

#include <stdio.h>
#include <stdlib.h>

struct customer {
   char  fname[30],lname[30];
   int   ac_num;
   float ac_balance;
};

void main ()
{
   FILE *fp;
   struct customer input;

   fp = fopen ("customer.dat","r");
   if (fp == NULL)
   {
      printf("\nFile reading error\n\n");
      exit (1);
   }

   while (fread (&input, sizeof(struct customer), 1, fp))
      printf ("Name = %s %s,   Acct Num = %d   Balance = %8.2f\n",
              input.fname, input.lname, input.ac_num, input.ac_balance);
}

Output of Program

Name = ABC PATEL,   Acct Num = 101   Balance = 55000.00
Name = XYZ SHAH,   Acct Num = 102   Balance = 50000.00

Writing Structure to data file



Following program will declare a Structure "customer". Program reads customer information and then writes into a "customer.dat" file.

#include <stdio.h>
//Define structure to store customer data.
struct customer
{
   char fname[30];
   char lname[30];
   int  ac_num;
   float ac_balance;
};

void main ()
{
   FILE *fp;
   //declare structure(customer) variable
   struct customer input;
   // open customer file for writing
   fp = fopen ("customer.dat","w");
   if (fp == NULL){
      printf("\nFile opening error..\n\n");
      exit (1);
     }

   printf("Enter \"exit\" as First Name to stop reading user input.");

   while (1)
     {
      printf("\nFirst Name: ");
      scanf ("%s", input.fname);
     
      if (strcmp(input.fname, "exit") == 0)
         exit(1);
     
      printf("Last Name : ");
      scanf ("%s", input.lname);
      printf("Account Number  : ");
      scanf ("%d", &input.ac_num);
      printf("Balance   : ");
      scanf ("%f", &input.ac_balance);

      // write customer data to customer.dat  file
      fwrite (&input, sizeof(struct customer), 1, fp);
     }
}

Output of program

Enter "exit" as First Name to stop reading user input.
First Name: ABC
Last Name : PATEL
Account Number  : 101
Balance   : 55000

First Name: XYZ
Last Name : SHAH
Account Number  : 102
Balance   : 50000


First Name: exit