program for defanging an IP address - c

Searching for program for defanging an IP address(only with strings)
EX:
Input : 12.34.57.34
Output : 12[.]34[.]57[.]34
#include<stdio.h>
#include<string.h>
int main()
{
char a[20],IP[3];
fgets(a,sizeof(a),stdin);
int s=strlen(a),i;
for(i=0;i<s;i++)
{
if(a[i]=='.')
{
a[i]=a[i+1];
printf("[.]);
}
printf("%c",a[i]);
}
return 0;
}
I've got close

if(a[i]=='.')
{
a[i]=a[i+1];
printf("[.]);
}
You replaced the dot with the number immediately after it, which I don't think is intended behavior:
123.123 becomes 1231123, so you'll be printing out 123[.]1123
Make it so that when you detect a dot, you just print out "[.]", and then go on to the next character (so basically just print "[.]" and do nothing). No need to replace the character, or print it out afterwards.

Related

I am trying to split this code into two .c and one .h file, but the structure is not getting accesssed by the other .c file

I have made a code which runs perfectly fine in a single file but when I try to split the code into two .c and one .h file the makefile shows an error of UNDEFINED REFERENCE TO THE STRUCTURE which is global data.
How can I split this code into the .c and .h file such that the error of undefined reference does not pop and code runs smoothly?
I just need the split .c and .h files,I can make the .mk file, I am a beginner in makefile.
Here the command line argument is the name of the file from which the code reads information-emplyoyeeinfo.txt.
The error while running the makefile(4 .c and 1 .h files) is in the screenshot below:
employeeinfo.txt file has these contents (user name, ID, password, casualleave, medical leave, earned leave)
Ramesh,QW120345,PO56,10,15,7
Rajesh,QW120905,IO56,10,15,7
Kajal,JI456987,IWQ9,10,15,7
Harleen,HJ782013,ZM12,10,15,7
Jim,BN784569,KL45,10,15,7`
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
//this code works on ZERO INDEXING
int linematched;//global variable which stores the variable
void main2();//this containsthe main part of the code workings,its pupose is explained below just before the function
void final_print();//prints the details of the user on quitting the wizard
void quit();//this is one function which handles the termination of code prompting the user to take another trail
void again();//this function handles the login if user wishes to take another leave
void table(char file_n[]);//populating the structure from data elements from the file by using specific delimiter
int login();//this function verifies the password with the one present in the file database
int deduction(int linematched,int days,int type_of_leave);//this performs another validation and deducts the days user desires for taking the leave
struct Empdetials
{
char name[25];
char id[9];//onr extra character to store /n
char password[5];
int casual;//casual,medical,earned leave as per the question
int medical;
int earned;
}emp[5];//declaring array of structures which will later be populated using table() function
void main(int argc,char *argv[])//command line arguments takes the name of the file to be read
{
char file_name[30];
strcpy(file_name,argv[1]);
printf("%s\n\n",file_name);
table(file_name);//calling the function to initiate the process of filling a structure with all the data from the files
printf("--------------------------------HELLO-------------------------------\n");
printf("----------------------WELCOME TO LEAVE MANEGMENT SYSTEM--------------\n");
main2();//the use of this is explained below
}
/*main function has a call to table() and invoking main() for re-login used to reset the structure and the deductions were lost,so I copied
everything of the main function into another function called main2() which is basically the amin function without he table() invoking so the
structure is not resetted after every call from again() and quit() during Re-login and structure keeps a track of the deductions that happened and
in this way I also removed the Welcome sentence to the same user,but he main reason is to avoid rewriting of the structure on every call
and losing the deduction data*/
void main2()
{
int casualm=10;//defining the maximum possible leaves here
int medicalm=15;
int earnedm=7;
int leave_days=0;//handles the number of leaves that a user will enter
int choice=0;//type of leave is handled by this variable 1 is casual,2 is emergency,3 is earned
int log=0;//CHECKS IF LOGIN WAS SUCCESFULL OR NOT
int res=0;//CHECKS IF DEDUCTION WAS SUCCESFULL OR NOT
//-------------------------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------------------------------------------
log=login();//login is invoked and log stores the value which determines wheter the ogin was succesful or not
if(log==1)//if log=1,implies that the login was succesful and the user was found
{
printf("PLEASE SELECT HE TYPE OF LEAVE YOU WANT TO TAKE\n");
printf("1.CASUAL LEAVE\n");
printf("2.MEDICAL LEAVE\n");
printf("3.EARNED LEAVE\n");
scanf("%d",&choice);
printf("PLEASE ENTER THE NUMBER OF LEAVES YOU WANT TO APPLY FOR\n");
scanf("%d",&leave_days);
}
else
{
printf("SORRY THE LOGIN CREDENTIALS DON'T MATCH WITH ANY USER\n\n\n");//when the login fails this message is displayed
again();//gives user another chance to take give the input
}
//first validation of the input values,this ompare the input with the largest value of holidays available
int flag=1;//this controls wheter the variable entetred is within the maximum limit and that decuction() function can be called
if(choice==1)
{
if(leave_days>casualm)
{
printf("THE ENTERED NUMBER OF DAYS CROSSES THE MAXIMUM LIMIT \n");
again();
flag=0;
}
}
else if(choice==2)
{
if(leave_days>medicalm)
{
printf("THE ENTERED NUMBER OF DAYS CROSSES THE MAXIMUM LIMIT \n");
again();
flag=0;
}
}
else if(choice==3)
{
if(leave_days>earnedm)
{
printf("THE ENTERED NUMBER OF DAYS CROSSES THE MAXIMUM LIMIT \n");
again();
flag=0;
}
}
else
{
printf("sorry!! wrong input\n");
again();
flag=0;
}
if(flag)//if the validation is succcesful the value of the variable remains 1 and this loop is entered
{
res=deduction(linematched,leave_days,choice);//if res==1 then thern the validation was succesful and then the deduction is called and parameter is passed
if(res==1)//if deduction was succesful then the
{
printf("DEDUCTION WAS SUCCESFUL\n\n");
again();
//final_print();
}
}
}
//I am trying to convert the file to a structure and then use the structure to access the data and I'm also using files to store the information
extern void table(char file_n[])//this function is responsible for populating the structure by reading the file
{
printf("%s\n\n",file_n);
FILE *fp;//definig a file pointer
char ch;
char line[256];//definig 256 here,any arbitary number can be used
char *token;//token pointer that points to the elements of a line
int tokenposition=0;//token here means the particular text separated by comma
int lineposition=0;//line here is the entire line which has entire details of the an emmployee
fp=fopen(file_n,"r");//opening the file in read mode as we are only accessing information and not rewrting it
//-------------------------------------------------------------------------------------------------------------------------------------------------
while(fgets(line,256,fp) !=NULL) //accessing the lines one by one and trying to recognize the end of a line
{
tokenposition=0;//when we tokenize the line we need the count to keep a track of where we are int he string
//printf("%s \n",line);//used to check which line is not being read by the compiler
token = strtok(line,",");
//this seperates a line into token(entity) based on a delimiter,here the delimiter is a comma
//strtok-tring tokenization method
while(token != NULL)
{
switch(tokenposition)//acessing the required element through the tokenposition counter
{
case 0://NAME
strcpy(emp[lineposition].name,token);
break;
case 1://ID
strcpy(emp[lineposition].id,token);
break;
case 2://PASSWORD
strcpy(emp[lineposition].password,token);
break;
case 3://CASUAL LEAVE
emp[lineposition].casual=atoi(token);
break;
case 4://MEDICAL LEAVE
emp[lineposition].medical=atoi(token);
break;
case 5://EARNED LEAVE
emp[lineposition].earned=atoi(token);
break;
}
token =strtok(NULL,",");
tokenposition++;//to access the next token in the same line
}
lineposition++;//after all the tokens are put in a structure,wwe move to the next line and redo the entire process of reading a line
}
}
int login()
{
int i;//for the loop
char userid[9];//user ID int he majn function,this will be passed to the the login function
char userpassword[5];//user password in the main function
printf("ENTER YOUR 8 CHARACTER USER ID\n");
scanf("%s",userid);
printf("ENTER THE 4 CHARACTER PASSWORD\n");
scanf("%s",userpassword);
linematched=0;
for(i=0;i<5;i++)
{
if((strcmp(emp[i].id,userid)==0)&&(strcmp(emp[i].password,userpassword)==0))//checking if login credentils are corre3ct or wrong
{
linematched=i;
printf("WELCOME %s TO THE LEAVE MANEGMENT SYSTEM\n",emp[linematched].name);
return 1;//TO INDICATE THAT USER WAS FOUND AND LOGIN WAS SUCCESFUL
break;
}
}
}
int deduction(int linematched,int days,int type_of_leave)//here all inputs are validated for the second time after the validation in main function
{
switch(type_of_leave)
{
case 1://casual leave
{
if(days>emp[linematched].casual)
{
printf("SORRY YOU HAVE EXHAUSTED YOUR LEAVE QUOTA\n\n");
again();
return 0;
break;
}
else
{
emp[linematched].casual=emp[linematched].casual-days;
return 1;
break;
}
break;
}
case 2://medical leave
{
if(days>emp[linematched].medical)
{
printf("SORRY YOU HAVE EXHAUSTED YOUR LEAVE QUOTA\n\n");
again();
return 0;
break;
}
else
{
emp[linematched].medical=emp[linematched].medical-days;
return 1;
break;
}
break;
}
case 3://earned leave
{
if(days>emp[linematched].earned)
{
printf("SORRY YOU HAVE EXHAUSTED YOUR LEAVE QUOTA\n\n");
again();
return 0;
break;
}
else
{
emp[linematched].earned=emp[linematched].earned-days;
return 1;
break;
}
break;
};
};
}
void quit()
{
char ans[5];
printf("ARE YOU SURE YOU WANT TO QUIT THE WIZARD? Y OR N\n");
scanf("%s", ans);
if (tolower(ans[0]) == 'y')
{
final_print();
printf("\n\n");
printf("---THANK YOU FOR USING OUR PORTAL--\n");
}
else
{
main2();
}
}
void again()
{
char ans1[5];
printf("SEARCH AGAIN USING ID AND PASSWORD? Y OR N\n");
scanf("%s", ans1);
if (tolower(ans1[0]) == 'y')
{
main2();//FOR RE-LOGIN PROCESS
}
else
{
quit();
}
printf("\n\n\n\n\n\n");
}
void final_print()
{
printf("----------------FINAL STATEMENT OF LEAVE OF EACH EMPLOYEE------------------------\n\n");
int i;
for (i = 0; i < 5; i++)
{
printf("NAME : %s\n",emp[i].name);
printf("USER ID : %s\n",emp[i].id);
printf("CASUAL LEAVE LEFT : %d\n",emp[i].casual);
printf("MEDICAL LEAVE LEFT : %d\n",emp[i].medical);
printf("EARNED LEAVE LEFT : %d\n\n",emp[i].earned);
}
printf("---------THANK YOU FOR USING LEAVE MANEGMENT PORTAL-----\n");
}
With
struct Empdetials
{
char name[25];
char id[9];//onr extra character to store /n
char password[5];
int casual;//casual,medical,earned leave as per the question
int medical;
int earned;
}emp[5];
you do basically two things in one step: (1) define struct Empdetials and (2) define a variable emp; Note that you cannot define a global variable in a headerfile, at least if you intend to include this header file in different .c-files.
You will need to separate the definition of struct Empdetials, the declaration of a global variable emp and the definition of this global variable in exactly one translation unit (i.e. exactly one .c-file). Note the extern-keyword in emp.h, which declares that emp will be defined once elsewhere (i.e. in emp.c later):
emp.h:
struct Empdetials
{
char name[25];
char id[9];//onr extra character to store /n
char password[5];
int casual;//casual,medical,earned leave as per the question
int medical;
int earned;
};
extern struct Empdetials emp[5]; // declaration of emp
emp.c:
#include "emp.h"
struct Empdetials emp[5]; // definition of emp
int main() { ...
again_final.c:
#include "emp.h"
// Note: no struct Empdetials emp[5]; any more...
again() { ...
login.c:
#include "emp.h"
// Note: no struct Empdetials emp[5]; any more...
login() { ...

C linear search failing to compare two strings using strcmp, compiles fine

The program runs and exits with code 0, but gives no output, it's supposed to be a linear search program
I looked to other similar problems, i tried to end the array with \n. tried instead of just relying in just the "if (strcmp=0)" to make something with the values strcmp return, I'm very new and for what I'm learning not very good, just made things worst, i tried to look if it was about the char* values strcmp expect, but couldn't find the problem
#include <stdio.h>
#include <string.h>
#define max 15
int lineal(char elementos[], char elebus)
{
int i = 0;
for(i=0; i<max; i++)
{
if(strcmp(elementos[i], elebus)==0)
{
printf("Elemento encontrado en %d,", i); //element found in
}
else
{
printf("elemento no encontrado"); //not found
}
}
}
int main()
{
char elebus[50];
char elementos[max][50]= {"Panque", "Pastel", "Gelatina", "Leche", "Totis", "Tamarindo" "Papas", "Duraznos", "Cacahuates", "Flan", "Pan", "Yogurt", "Café", "Donas", "Waffles"};
printf("Escribir elemento a buscar\n");
scanf("%s", elebus);
int lineal(char elementos[], char elebus);
}
The expected output would be element found in "i" position, if found
if not found print "not found"
You want to pass it a string to find, not just one character Also, elementos should be a 2D array. Change the signature of your function to this:
int lineal(char elementos[max][50], char *elebus)
Also, in main, you don't call the function. Instead, you just declare it again. call it like this:
lineal(elementos, elebus);
Furthermore, I would change it to return void instead of int. You're neither returning anything (that's undefined behavior) nor are you using the return value anywhere. But I assume that this isn't the final version and you want to return the index at some point.
On a side note, right now it's printing that it didn't find the element for every time it didn't match, even if it does find it eventually. I would recommend this instead:
for (i = 0; i < max; i++)
{
if (strcmp(elementos[i], elebus) == 0)
{
printf("Elemento encontrado en %d\n,", i); //element found in
return;
}
}
printf("elemento no encontrado\n"); //not found
This is printing "elemento no encontrado" only once, and only when the string wasn't found.

can someone help me with my c code

Hello so i am creating a program that reads from a file and outputs each category of the things in the text in sorted for example i want it to output like this :
Company name: air france Date of creation: 06281957 Flight number: AT6801 Incoming city: london Arrival city: paris Amount of fuel liters left: 380 Plane category: B777
this is the input :
air qatar06281957AT680londonmadrid380B777 turkish airlines05201933TK1298istanbulmadrid250A380 lufthansa01061953LH29frankfurtmadrid75B747 air canada06281957AT7245ammanmadrid120A320 turkish airlines05201933TK1266dohamadrid522A320 air france10071933AF123parismadrid105B777 -1
The code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
FILE *inp,*outp;
int i,j,c=0,l,c2=0,c3=0;int c4=0;int c5=0,c6=0,k,m,c7=0,flag=0;int c8=0,c9=0,c10=0,flag2=0,n,c11=0,c12=0,c13=0,c14=0,p=0,c15=0,c16=0,t,t1,t2,t3,t4,t5,t6,t7,s;
char ultimate_array[600];char plane[100][6];char date[600][6];char nflight[600][6];char destination[100][6];char fuel [100][6];char planetype [100][6];
inp=fopen("input.txt","r");
for(i=0;!feof(inp);i++)
{
fscanf(inp,"%c",&ultimate_array[i]);
}
s=strlen(ultimate_array);
for(i=0;i<s;i++)
{
printf("%c",ultimate_array[i]);
}
printf("\n\n\n\n\n\n\n\n\n\n\n\n");
for(t=0;t<6;t++)
{
for(j=0;j<200;j++)
{
c++;
if(isdigit(ultimate_array[j]))
{
c3=c;
while(c>=0)
{
plane[t][c]=ultimate_array[j];
c--; j--;
}
break;
}
}
for(k=0;k<200;k++)
{
c2++;
if(isupper(ultimate_array[k]))
{
c5=c2; c2=c2-c3; c9=c2;
while(c2>=0)
{
date[t][c2]=ultimate_array[k];
k--; c2--;
}
break;
}
}
for(l=c3;l<200;l++)
{
c4++;
if(islower(ultimate_array[l]))
{
c4=c4+c3-c5;
while(c4>=0)
{
while(flag==0)
{
c8=c4; c6=c4+c5; flag=1;
}
nflight[t][c4]=ultimate_array[l];
c4--; l--;
}
break;
}
}
c10=c9+c8;
for(m=c6;m<200;m++)
{
c7++;
if(isdigit(ultimate_array[m]))
{
c7--;m--;
while(c7>=0)
{
while(flag2==0)
{
c13=c7; flag2=1;
}
destination[t][c7]=ultimate_array[m];
c7--; m--;
}
break;
}
}
for(n=c14;n<200;n++)
{
c11++; c14=c3+c13+c10;
if(isupper(ultimate_array[n]))
{
c12=c11; c11=c11-1;
while(c11>=0)
{
fuel[t][c11]=ultimate_array[n];
c11--; n--;
}
break;
}
}
c15=c14+c12;
for(p=c15;p<200;p++)
{
c16++;
if(ultimate_array[p]=='\n')
{
while(c16>=0)
{
planetype[t][c16]=ultimate_array[p];
c16--; p--;
}
break;
}
}
for(t1=0;t1<20;t1++)
{
printf(" %c",plane[t1][t]);
}
printf("\n");
for(t2=0;t2<100;t2++)
{
printf("%c",destination[t2][t]);
}
printf("\n");
for(t3=0;t3<100;t3++)
{
printf("%c",date[t3][t]);
}
printf("\n");
for(t4=0;t4<100;t4++)
{
printf(" %c",fuel[t4][t]);
}
printf("\n");
for(t5=0;t5<100;t5++)
{
printf(" %c",nflight[t5][t]);
}
printf("\n");
for(t6=0;t6<5;t6++)
{
printf(" %c",planetype[t][t6]);
}
}
return 0;
}
I have been struggling with a lot of things but I finally managed to separate every category to a different array, however , when I tried to do it for 2D array I always get garbage can someone point out what the mistake I did ?
we couldn't read in the input file and write it in a 2D array so the concept that i have used in this code i search in the array until i find something that would help me separate the word from the others such as 06281957 in the input i used isdigit to identify which index has it then i copy the previous characters into a new array this trick seemed to work for a 1d array however when i tried to scan it to 2d it stopped working and only random chars seemed to appeari wanted to print the whole 2d array of each category but i failed to do so, for the variables i used them as checkpoints for the next check to put the things i want in a new array. For minimizing the code i cant seem to find another solution to do so i know that my code is very big but if someone has a better idea it would be awesome.
One thing that will simplify your code is using scansets. It will make it much easier to extract and separate digits from non-digits, lower from upper case. Fixed width specifiers is also a concept you should read into. To see how many characters where extracted, use %n described in previous link. Examples:
/* ... */
inp=fopen("input.txt","r");
/* your code... */
for(i=0;!feof(inp);i++)
{
fscanf(inp,"%c",&ultimate_array[i]);
}
s=strlen(ultimate_array);
for(i=0;i<s;i++)
{
printf("%c",ultimate_array[i]);
}
/* ...can be replaced by something similar to this (untested) */
fscanf(inp, "%599s%n", ultimate_array, &s); /* read up to 599 characters, put number of read characters in s */
ultimate_array[s]=0; /* set null terminator */
char a[10]; sprintf(a, "%%%ds", s); /* create print format, e.g. "%123s" */
printf(a, ultimate_array) /* print 's' number of characters */
Make sure to take it slow as the lines can be hard to read initially. As you become more familiar with it I'm sure you will find scanf does "exactly what is needed" using no loops or conditions at all.
Don't use feof. Instead check the return value from scanf. If you try extract a single "something" from file using scanf and it returns 0 (zero arguments were filled), you are done reading the file.
Making 2D arrays is almost always wrong. Group your variables in structures:
typedef struct flights_t {
char plane[100];
char date[100];
/* ... */
} flights[6]; unsigned int nrOfFlights = 0;
int c[16];
int t[7];
Make symbolic constants instead of litering the code with copies of 20, 100 and 6 all over for improved readability and maintainance. You will also recieve much better help from forums such as SO.
Your posted code is sadly beyond saving without proper description of what each code section is supposed to do. Hopefully this "answer" will get you going making better code.

Weird error/result when running code... C fdtd method

Whenever I initiate a for loop to give values to an array, it modifies the result in another loop despite not being called in that loop... The problem comes from epsR... somehow commenting/uncommenting it changes the result for the time stepping loop (calculating the elec/mag field). Why? When the for loop with espR in and the if statement is left commented out, the results are good. When not commented out, I get nonsense results!
Could it be like memory corruption? I don't see what could be causing the problem.
#include <stdio.h>
#include <math.h>
#define SIZE 200
int main()
{
double ez[SIZE]={0.}, hy[SIZE]={0.}, imp0=377.0;
double epsR[SIZE];
int qTime, maxTime=650, mm;
char basename[80]="sim", filename[100];
int frame=0;
FILE *snapshot;
/* Init */
for (mm=0;mm<SIZE;mm++){
ez[mm]=0.0;
}
for (mm=0;mm<SIZE-1;mm++){
hy[mm]=0.0;
}
/* Leaving this loop uncommented modifies the results
of the loop time stepping*/
for (mm=0;mm<SIZE;mm++){
if (mm<100){
epsR[mm]=1.0;
}
else {
epsR[mm]=9.0;
}
}
/* time stepping*/
for (qTime=0; qTime<maxTime;qTime++){
/*Mag field*/
hy[SIZE-1]=hy[SIZE-2];
for (mm=0;mm<SIZE-1;mm++){
hy[mm]=hy[mm]+(ez[mm+1]-ez[mm])/imp0;
}
hy[49]-=exp(-(qTime-30.)*(qTime-30.)/100.)/imp0;
/*Elec field*/
ez[0]=ez[1];
ez[SIZE-1]=ez[SIZE-2];
for (mm=0;mm<SIZE;mm++){
ez[mm]=ez[mm]+(hy[mm]-hy[mm-1])*imp0/9.0;
}
ez[50]+=exp(-(qTime+0.5-(-0.5)-30.)*(qTime+0.5-(-0.5)-30.0)/100.);
/*Write*/
if (qTime % 10==0){
sprintf(filename,"%s.%d", basename, frame++);
snapshot=fopen(filename,"w");
for (mm=0;mm<SIZE;mm++){
fprintf(snapshot,"%g\n",ez[mm]);
}
fclose(snapshot);
}
}
return 0;
}
In this loop:
for (mm=0;mm<SIZE;mm++){
ez[mm]=ez[mm]+(hy[mm]-hy[mm-1])*imp0/9.0;
}
in the first iteration, mm == 0
so hy[mm-1] is hy[-1] and that's the out of bounds undefined behavior. Meaning anything can happen, because it's accessing random data.
If you want it to be accessing the last element, check like so:
for (mm=0;mm<SIZE;mm++){
if(mm==0) {
ez[0]=ez[0]+(hy[0]-hy[SIZE - 1])*imp0/9.0;
} else {
ez[mm]=ez[mm]+(hy[mm]-hy[mm-1])*imp0/9.0;
}
}

Assignment to write a program that gives the user a choice between two options - C

I have an assignment due and I am drawing a blank on what exactly to do... I'm sure it is simple but I havent quite gotten the hang of things yet. The assignment is -
Write a program that gives the user 2 menu options: either call a function that will print a greeting and your name 4 times or call a function that will count down from 10 to 0 and then print "Blastoff!". Both functions should use for loops to print the appropriate output.
I have the prompt and the functions done so far... but I am unsure of how to display one or the other depending on the choice the user makes. Thank you for your help.
#include <stdio.h>
int main (void){
// declare counter variable
int i;
// prompt the user to make a choice
printf("What would you like to do?\n 1. Print my name\n 2. Count down from 10\n");
printf("\n");
// display greeting and name 4 times
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
printf("Blastoff!");
}
You should read the input from user's keyboard:
int c;
c = getchar();
if (c == '1')
{
// display greeting and name 4 times
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
}
if (c == '2')
{
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
}
printf("Blastoff!");
you should use Switch case.
switch(choice) {
case 1: //first for loop
break;
case 2: //second for loop
break;
}
Looks like you are missing a couple of points here. Firstly, you have not yet written any functions. Try looking here to gain some insight on that front.
Secondly, to make a choice based on user input you need to actually get that input somehow. You'll probably want to use scanf.
Lastly, once you have the user's input (say, in a variable declared as int input;) you can use if to control the flow of your program based on that variable like this:
if(input == 1){
greet();
}
else {
countDown();
}
Cheers! If you have any further questions feel free to comment below.
First of all you haven't actually declared you functions. Functions in C should be declared like the main function is. For more info in this see here.
// display greeting and name 4 times
void greeting(){
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
}
void countdown() {
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
printf("Blastoff!");
}
To get the user's input the most common way is by keyboard. scanf accomplishes that in C. Details on scanf here
int main(void){
int i, choice;
//prompt the user to make a choice
// You don't need 2 printf for the newlines stick them to one.
printf("What would you like to do?\n 1. Print my name\n 2. Count down from 10\n\n");
//This takes the user's input and puts it in the variable choice
scanf(%d, &choice);
}
Lastly to decide what to do based on the user input you can use either an if then else statement or a switch. I will provide a solution with an if statement and you can figure the one with the switch on your own. Your final code should look like this.
int main(void){
int i, choice;
//prompt the user to make a choice
// You don't need 2 printf for the newlines stick them to one.
printf("What would you like to do?\n 1. Print my name\n 2. Count down from 10\n\n");
//This takes the user's input and puts it in the variable choice
scanf(%d, &choice);
if(choice == 1){
greeting();
}else{
countdown();
}
}
// display greeting and name 4 times
void greeting(){
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
}
void countdown() {
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
printf("Blastoff!");
}
Bear in mind that this code has a lot of flaws (error checking mainly) but I guess your assigment is not about that.
First of all you need to include libraries with function you will need. You do this by
#include <someLibrary.h>
at the beggining of you document. Libraries mostly have .h extension. Always look for them if you try to do something. You consider them to have best performance and functionality as possible (not always true).
What is next you declare your functions. Function has name, arguments which are going into it, body in which they do something and return value (can be float, int, char etc). If function doesnt return anything, they return void (dont have return at the end). You declare functions before main() with only types of arguments. Whole body is after main (it is better looking).
If you declared function with arguments, you have to provide these arguments to function in () brackets. Even if no arguments are needed, you use them like getch() in example below. Note that function become what it return. If you declared some new variables in function they will be visible only in function. On the other hand function will not see any variable from other function (main too). If you want so, declare global variables (not recommended).
#include <stdio.h>
#include <conio.h> //libraries
void function1(int);
float function2(float); //declaration of functions
int main()
{
char decision;
printf("press 'a' to run function1, press 'b' to run function2\n");
decision=getch(); //first see getch()? look in google for functionality and library !
int someInt=10;
float someFloat=11;
if(decision== 'a')
{
function1(someInt);
}
else if(decision == 'b')
{
printf("%f", funcion2(someFloat)); //example that function become what they return
}
else
{
printf("No decision has been made");
}
getch(); //program will wait for any key press
return 0;
}
void function1(int param1)
{
//print your stuff // this function return void, so doesnt have return; statement
}
float function2(float param1)
{
return 2*param1; //this function have to return some float
}

Resources